import { reqCartList, reqDeleteCartById, reqUpdateCheckedById } from '@/api';
const actions = {
  // 获取购物车列表数据
  async getCartList({ commit }) {
    let result = await reqCartList()
    if (result.code === 200) {
      commit('GETCARTLIST', result.data)
    }
  },
  // 删除购物车数据
  async deleteCartListById({ commit }, skuId) {
    let result = await reqDeleteCartById(skuId)
    if (result.code == 200) {
      return "删除成功"
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 切换单个商品选中状态
  async updateCheckedById({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedById(skuId, isChecked)
    if (result.code == 200) {
      return "ok"
    } else {
      return Promise.reject(new Error("faile"))
    }
  },
  // 删除全部选中的商品
  deleteAllCheckedCart({ dispatch, getters }) {
    let PromiseAll = []
    getters.cartList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch("deleteCartListById", item.skuId) : ""
      PromiseAll.push(promise)
    });
    // 如果都成功返回成功   如果有一个失败返回失败
    return Promise.all(PromiseAll)
  },
  // 全选按钮功能
  updateAllCartChecked({ dispatch, state }, isChecked) {
    let promiseAll = []
    state.cartList[0].cartInfoList.forEach(item => {
      let promise = dispatch("updateCheckedById", { skuId: item.skuId, isChecked })
      promiseAll.push(promise)
    })
    return Promise.all(promiseAll)
  }
}
const mutations = {
  // 获取购物车列表数据
  GETCARTLIST(state, cartList) {
    state.cartList = cartList
  }
}
const getters = {
  cartList(state) {
    return state.cartList[0] || {}
  },
}
const state = {
  cartList: []
}

export default {
  state,
  actions,
  mutations,
  getters
}
